﻿using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;
using System.Net;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Drawing;

namespace Dandan
{
    public partial class LoginForm : System.Windows.Forms.Form
    {
        [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
        private static extern IntPtr CreateRoundRectRgn
            (
                int nLeftRect,
                int nTopRect,
                int nRightRect,
                int nBottomRect,
                int nWidthEllipse,
                int nHeightEllipse
             );

        [DllImport("dwmapi.dll")]
        public static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);

        [DllImport("dwmapi.dll")]
        public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);

        [DllImport("dwmapi.dll")]
        public static extern int DwmIsCompositionEnabled(ref int pfEnabled);

        private bool m_aeroEnabled;
        private const int CS_DROPSHADOW = 0x00020000;
        private const int WM_NCPAINT = 0x0085;
        private const int WM_ACTIVATEAPP = 0x001C;

        public struct MARGINS
        {
            public int leftWidth;
            public int rightWidth;
            public int topHeight;
            public int bottomHeight;
        }

        private const int WM_NCHITTEST = 0x84;
        private const int HTCLIENT = 0x1;
        private const int HTCAPTION = 0x2;
        
        private string _userName;
        private string _password;
        public static LoginForm LoginFormIstance;

        protected override CreateParams CreateParams
        {
            get
            {
                m_aeroEnabled = CheckAeroEnabled();

                CreateParams cp = base.CreateParams;
                if (!m_aeroEnabled)
                    cp.ClassStyle |= CS_DROPSHADOW;

                return cp;
            }
        }

        private bool CheckAeroEnabled()
        {
            if (Environment.OSVersion.Version.Major >= 6)
            {
                int enabled = 0;
                DwmIsCompositionEnabled(ref enabled);
                return (enabled == 1) ? true : false;
            }
            return false;
        }

        public LoginForm()
        {
            m_aeroEnabled = false; //窗体四边阴影
            InitializeComponent();
            this.Load += OnLoginFormLoaded;
            this.VisibleChanged += OnLoginFormVisibleChanged;
            LoginFormIstance = this;
        }

        private void OnLoginFormVisibleChanged(object sender, EventArgs e)
        {

        }

        private void OnLoginFormLoaded(object s, EventArgs e)
        {

        }
        

        /// <summary>
        /// 执行登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnLoginButtonClicked(object sender, EventArgs e)
        {
           
        }
        
        /// <summary>
        /// 发布登录通知
        /// </summary>
        void PublishLoginEvent()
        {
        }
        

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void LoginForm_Load(object sender, EventArgs e)
        {

        }

        public static String TBappsecret = "u3ChVYsEOFJbCBgE0E5W6sKWiYEi2PxHpMexvxxe";
	    public static String TBappid = "3";
        private void panel1_Click(object sender, EventArgs e)
        {
            /*string postString = string.Format("appid={0}&appsecret={1}&identifier={2}&credential={3}", TBappid, TBappsecret, "15183334590", "nicaibudao");
            RestApiClient HttpClient = new RestApiClient("https://tinyboss.cn/api/login",HttpVerbNew.POST, (new ContentType()).JSON, postString);
            string json = HttpClient.MakeRequestPost();
            LoginData login = JsonConvert.DeserializeObject<LoginData>(json);
            MessageBox.Show(json);*/
            //HttpHelper Http = new HttpHelper();
            //Http.HttpVisit("https://tinyboss.cn/api/login",true,postString,0,null,null,null);

            string loginUrl = "/api/login";

            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("appid", "3");
            parameters.Add("appsecret", "u3ChVYsEOFJbCBgE0E5W6sKWiYEi2PxHpMexvxxe");
            parameters.Add("identifier", UserNameComboBox.Text);
            parameters.Add("credential", textBox2.Text);
            string json = HttpWebResponseUtility.MakeRequestPost(loginUrl, parameters);
            try
            {
                LoginData login = JsonConvert.DeserializeObject<LoginData>(json);
                LoginData.SetLoginData(login);
                GetUserData();
            }
            catch (Exception)
            {
                MessageBox.Show("系统提示"+json);
            }
            //MessageBox.Show(login.data.token);
        }

        public void GetUserData()
        {
            string Url = "/api/v1/profile";

            string json = HttpWebResponseUtility.MakeRequestGet(Url);
            try
            {
                UserData UserData = JsonConvert.DeserializeObject<UserData>(json);
                //OrderData.SetData(orderData);
                UserData.SetData(UserData);
                this.BeginInvoke((MethodInvoker)delegate ()
                {
                    this.Hide();
                    MainForm1 fm1 = new MainForm1();
                    fm1.Show();
                    //FromMain frmMain = new FromMain();
                    //frmMain.Location = new Point(Screen.GetWorkingArea(this).Width - 400, 50);
                    //frmMain.Show();
                });
            }
            catch (Exception)
            {
                MessageBox.Show("系统提示" + json);
            }
        }

        private void panel3_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture(); //释放鼠标捕捉
                SendMessage(Handle, 0xA1, 0x02, 0);
            }
        }

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_NCPAINT:
                    if (m_aeroEnabled)
                    {
                        var v = 2;
                        DwmSetWindowAttribute(this.Handle, 2, ref v, 4);
                        MARGINS margins = new MARGINS()
                        {
                            bottomHeight = 1,
                            leftWidth = 1,
                            rightWidth = 1,
                            topHeight = 1
                        };
                        DwmExtendFrameIntoClientArea(this.Handle, ref margins);

                    }
                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
            //全窗体点击：最大化、最小化、移动窗体、双击最大化
            /*
            if (m.Msg == WM_NCHITTEST && (int)m.Result == HTCLIENT)
                m.Result = (IntPtr)HTCAPTION;
            */
        }
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
    }
}
